package xyz.zhzby.cyzx.servicebase.domain;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.Data;

/**
 * @author zby
 * @date 2021/12/06
 */
@Data
@JsonInclude(Include.NON_NULL)
@ApiModel("响应通用参数包装")
public class RestResponse<T> {

    public static final Integer SUCCESS = 0;

    @ApiModelProperty("响应错误编码,0为正常")
    private Integer code;

    @ApiModelProperty("响应错误信息")
    private String msg;

    @ApiModelProperty("响应内容")
    private T result;

    public boolean isSuccess() {
        return SUCCESS.equals(this.code);
    }

    public static <T> RestResponse<T> success() {
        return new RestResponse();
    }

    public static <T> RestResponse<T> success(T result) {
        RestResponse<T> response = new RestResponse();
        response.setResult(result);
        return response;
    }

    public static <T> RestResponse<T> success(String msg, T result) {
        RestResponse<T> response = new RestResponse();
        response.setResult(result);
        response.setCode(200);
        response.setMsg(msg);
        return response;
    }

    public static <T> RestResponse<T> success(Integer code, String msg, T result) {
        RestResponse<T> response = new RestResponse();
        response.setResult(result);
        response.setCode(code);
        response.setMsg(msg);
        return response;
    }

    /**
     * 返回失败信息
     *
     * @param msg 失败信息
     * @param <T>
     * @return
     */
    public static <T> RestResponse<T> fail(String msg) {
        RestResponse<T> response = new RestResponse();
        response.setCode(-2);
        if (msg == null) {
            //传来的msg可能为null，就没有了。所以提前处理
            msg = "操作失败，请稍后重试";
        }
        response.setMsg(msg);
        return response;
    }

    /**
     * 返回失败信息，指定错误编码
     *
     * @param code
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> RestResponse<T> fail(Integer code, String msg) {
        RestResponse<T> response = new RestResponse();
        response.setCode(code);
        response.setMsg(msg);
        return response;
    }

    public RestResponse() {
        this(0, "success", null);
    }

    public RestResponse(Integer code, String msg) {
        this(code, msg, null);
    }

    public RestResponse(Integer code, String msg, T result) {
        this.code = code;
        this.msg = msg;
        this.result = result;
    }

}
